﻿#include"Heap.h"

//默认初始化堆
void HPInit(HP* php)
{
	assert(php);
	php->arr = NULL;
	php->capacity = php->size = 0;
}

//堆的销毁
void HPDestroy(HP* php)
{
	assert(php);
	if (php->arr)
		free(php->arr);

	php->arr = NULL;
	php->capacity = php->size = 0;
}

void swap(int* x, int* y)
{
	int tmp = *x;
	*x = *y;
	*y = tmp;
}

void AdjustUp(HPDataType* arr,int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (arr[child] < arr[parent])
		{
			swap(&arr[child], &arr[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
//堆的插⼊
void HPPush(HP* php, HPDataType x)
{
	assert(php);
	//扩容
	if (php->capacity == php->size)
	{
		int newcapacity = php->capacity == 0 ? 4 : 2 * php->capacity;
		HPDataType* tmp = (HPDataType*)realloc(php->arr, newcapacity * sizeof(HPDataType));
		if (tmp == NULL)
		{
			perror("realloc fail!");
			exit(1);
		}
		php->arr = tmp;
		php->capacity = newcapacity;
	}
	php->arr[php->size] = x;

	AdjustUp(php->arr, php->size);

	++php->size;
}

void AdjustDown(HPDataType* arr, int parent, int n)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		//小堆：找左右孩子中找最小的
		//大堆：找左右孩子中找大的
		if (child + 1 < n && arr[child] > arr[child + 1])
		{
			child++;
		}
		if (arr[child] < arr[parent])  //小堆，什么时候交换？ 孩子比父亲小
		{
			swap(&arr[child], &arr[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

//堆的删除
void HPPop(HP* php)
{
	assert(php && php->size);

	swap(&php->arr[0], &php->arr[php->size - 1]);

	--php->size;

	AdjustDown(php->arr, 0, php->size);
}

// 判空
bool HPEmpty(HP* php)
{
	assert(php);
	return php->size == 0;
}

//出堆数据
HPDataType HPTop(HP* php)
{
	assert(php && php->size);

	return php->arr[0];
}
